package com.glodon.paas.consumer.service;

import com.glodon.paas.security.oauth1.OAuthConsumerEx;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.exception.OAuthException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Don Li
 */
public class OAuthServlet extends HttpServlet {

    @Value("${oauth.request.url}")
    private String providerRequestUrl;

    @Value("${oauth.access.url}")
    private String providerAccessUrl;

    @Value("${oauth.authorize.url}")
    private String providerAuthorizeUrl;

    @Value("${oauth.consumer.key}")
    private String consumerKey;

    @Value("${oauth.consumer.secret}")
    private String consumerSecret;

    @Value("${oauth.consumer.callback}")
    private String consumerCallBack;

    @Override
    public void init(ServletConfig config) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final OAuthConsumer consumer = new OAuthConsumerEx(consumerKey, consumerSecret);
        final OAuthProvider provider = new DefaultOAuthProvider(providerRequestUrl, providerAccessUrl, providerAuthorizeUrl);
        String url;
        // retrieve the request token and authorization url
        try {
            url = provider.retrieveRequestToken(consumer, consumerCallBack);
        } catch (OAuthException e) {
            throw new ServletException("oauth failed", e);
        }
        req.getSession().setAttribute("provider", provider);
        req.getSession().setAttribute("consumer", consumer);
        // redirect user to provider for authorization
        resp.sendRedirect(url);
    }
}
